class Topic < ActiveRecord::Base
  belongs_to :user
  validates :title, :presence => true
  has_many :blog_posts
  attr_accessible :guest_ok, :public, :published, :title, :user_id
  scope :published, where(:published => true)
  scope :public_visible, where(:published => true, :public => true)

  BRIEF_LENGTH = 30

  def to_s
    title
  end

  def brief_title
    title_chars = title.split("")
    return "#{title_chars[0,BRIEF_LENGTH - 3]}..." if title_chars.count > BRIEF_LENGTH
    title
  end

  def self.visible_to(user)
    where("user_id = #{user.id} OR (public = true AND published = true)")
  end

  def allowed_to?(user)
    return true if self.user == user
    return false unless self.public && self.published
    true
  end

  def allowed_to_add?(user)
    return true if self.user == user
    return false unless self.public && self.published
    return false unless self.guest_ok
    true
  end
end
